<?php
namespace ucenter\client\controllers;

use Yii;
use services\ucenter\UserService;
use heihei\rest\Controller;

use heihei\helpers\HttpClientHelper;
use heihei\libs\weixin\MP as WeixinMP;


/**
 * 登陆控制器
 */
class LoginController extends Controller
{
    /**
     * 登录注册
     *
     * @return string
     */
    public function actionLogin()
    {
        
    }

    /**
     * 微信小程序
     *
     * @return string
     */
    public function actionWxMiniProgram()
    {
        $request = Yii::$app->getRequest();
        $code = $request->post('code');
        if(!$code){
            return $this->fail("code必传！");
        }
        
        $wxmp = new WeixinMP([
            'appid' => 'wx1a4b112440df7c69',
            'secret' => 'f520694e80939ac59c4fedcd34f02ce0'
        ]);

        /*$wxmp = new WeixinMP([
            'appid' => 'wxe84d1fab98fba93c',
            'secret' => 'f913de53c6e12ce215d962bd54670a0b'
        ]);*/

        
        $sns = $wxmp->get('sns');
        $result = $sns->jscode2session($code);
        if(isset($result['errcode']) && $result['errcode'] > 0){
            return $this->fail('获得临时登录凭证失败:' . $result['errmsg']);
        }
        if($user = UserService::getUserByWeixinOpenid($result['openid'])){
            $result['user_id'] = $user->id;
            $result['is_login'] = 0;
        }
        else{
            $result['login_status'] = 1;
        }
        
        return $result;
    }
}
